//
//  CZRefreshControl.swift
//  Weibo28
//
//  Created by Apple on 16/5/16.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

enum RefreshState: Int {
    //  下拉刷新
    case Normal = 0
    //  松手就刷新
    case Pulling = 1
    //  正在刷新
    case Refreshing = 2
    
}

//  当前刷新控件的高度
let RefreshControlH: CGFloat = 50

class CZRefreshControl: UIControl {
    //  当前滚动的视图
    private var currentScrollView: UIScrollView?
    //  设置刷新状态
    private var refreshState: RefreshState = .Normal {
        didSet {
            switch refreshState {
            case .Normal:
                //  显示下拉刷新文本，停止菊花转，按钮重置动画
//                print("显示下拉刷新文本，显示箭头，停止菊花转，按钮重置动画")
                iconView.hidden = false
                messageLabel.text = "下拉刷新"
                indicatorView.stopAnimating()
                //  重置箭头
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconView.transform = CGAffineTransformIdentity
                })
                
                //  判断上一次是刷新状态，设置为原始的contentInset
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.currentScrollView?.contentInset.top -= RefreshControlH
                    })
                }
                
                
            case .Pulling:
//                print("显示松手就刷新文本，箭头调转")
                messageLabel.text = "松手就刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing:
//                print("显示正在刷新文本，菊花转起来，下拉箭头隐藏")
                messageLabel.text = "正在刷新"
                iconView.hidden = true
                indicatorView.startAnimating()
            
                //  发送事件
                sendActionsForControlEvents(.ValueChanged)
            
                //  设置停留
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.currentScrollView?.contentInset.top += RefreshControlH
                })
            }
        }
    }
    
    //  icon
    private lazy var iconView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //  菊花转
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    //  消息文本
    private lazy var messageLabel: UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 12)
        label.text = "下拉刷新"
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = UIColor.redColor()
        //  添加控件
        addSubview(iconView)
        addSubview(indicatorView)
        addSubview(messageLabel)
        //  设置约束
        iconView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-35)
            make.centerY.equalTo(self)
        }
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(iconView)
        }
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(iconView.snp_trailing)
            make.centerY.equalTo(self)
        }
    }
    
    //  设置当前控件的frame, 将要添加到那个父视图上
    override func willMoveToSuperview(newSuperview: UIView?) {
        //  判断我们的父视图能否强转成我们需要的滚动视图，如果可以我们可以监听tableview的一个滚动使用kvo
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        //  设置frame
        self.frame.size = CGSize(width: scrollView.frame.size.width, height: RefreshControlH)
        self.frame.origin.y = -RefreshControlH
        
        //  kvo监听
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
        //  记录添加的滚动视图
        currentScrollView = scrollView
    }
    
    //  kvo监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //  监听的就是可以滚动的视图，如果获取可以使用全局变量记录
//        print(currentScrollView!.contentOffset.y)
        
        //  接下来的操作判断状态
        if currentScrollView!.dragging {
            //  计算临界点
            let maxY = -(currentScrollView!.contentInset.top + RefreshControlH)
            //  y轴偏移量
            let contentOffSetY = currentScrollView!.contentOffset.y
            //  如果当前的偏移量小于临界点则是pulling状态
            if contentOffSetY < maxY  &&  refreshState == .Normal {
//                print("pulling")
                refreshState = .Pulling
            } else if contentOffSetY >= maxY && refreshState == .Pulling {
//                print("normal")
                refreshState = .Normal
            }
        } else {
            //  判断上一次是pulling状态在进入刷新状态
            if refreshState == .Pulling {
//                print("刷新状态")
                refreshState = .Refreshing
            }
        }
       
        
        
    }
    //  结束刷新
    func endRefreshing() {
        refreshState = .Normal
    }

    //  移除kvo
    deinit {
        //  移除kvo
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    
    }
    

}
